<?php

/**
* user_comic 会员操作类
*/

class user_comic {
	
	public static $userInfo;
	
	public function __construct() {
		//$this->loader();
		$this->autoLogin();
	}
	
	protected function loader() {
		
	}
	
	public function login() {
		$user = isset($_POST['user']) ? $_POST['user'] : false;
		$password = isset($_POST['password']) ? $_POST['password'] : false;
		
		$pregUser = '/^[\w-\@\.]{3,30}$/';
		$pregPass = '/^[\w-]{6,18}$/';
		$pregEmail = '/^([\w\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})$/';
		$condition = 'user_name';
		
		if (!preg_match($pregUser, $user)) {
			$msg = '账户格式不正确'; // mb_convert_encoding('账户格式不正确', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		if (preg_match($pregEmail, $user)) {
			$condition = 'email';
		}
		if (!preg_match($pregPass, $password)) {
			$msg = '密码必须为6至18位的英文数字下划线'; //mb_convert_encoding('密码必须为6至18位的英文数字下划线', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		$chkPass = encrypt_pass($password);
		$userArr = array('user' => $user, 'password' => $chkPass, 'type' => $condition);
		$userRow = $this->_doLogin($userArr);
		if (!$userRow) {
			$msg = '登陆失败,密码或用户名不正确'; //mb_convert_encoding('登陆失败,密码或用户名不正确', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		$time = time() + 3600 * 24 * 365 * 5;
		setcookie('user_id', base64_encode($userRow['user_id']), $time);
		setcookie('user_name', base64_encode($userRow['user_name']), $time);
		setcookie('user_pass', base64_encode($userRow['password']), $time);
		$userInfoStr = JSON($userRow, TRUE);
		$msg = '登陆成功！'; //mb_convert_encoding('登陆成功！', 'UTF-8', 'CP936');
		die('{"status": "true", "msg": "' . $msg . '", "user": ' . $userInfoStr . '}');
	}
	
	protected function _doLogin($userArr) {
		if ($userArr['user'] == '' || $userArr['password'] == '' || $userArr['type'] == '') {
			return FALSE;
		}
		$db = System::database();
		//$sql_user = "SELECT user_id, user_name, password, email, sex FROM user WHERE {$userArr['type']} = '{$userArr['user']}' LIMIT 1";
		$userRes = $db->select('user', ['user_id', 'user_name', 'password', 'email', 'sex'], [$userArr['type'] => $userArr['user'], 'LIMIT' => 1]);
		$userRow = $userRes[0];
		if ($userRow['user_id'] < 1 || $userRow['password'] !== $userArr['password']) {
			//die($userRow['password'] .'---'. $userArr['password']);
			return FALSE;
		}
		$time = time();
		$ip = getIP();
		$sql_ud = "UPDATE user SET last_login = '$time', ip = '$ip' WHERE user_id = {$userRow['user_id']} LIMIT 1";
		$db->query($sql_ud);
		self::$userInfo = $userRow;
		return $userRow;
	}
	
	public function checkLogin() {
		$res = $this->_cookieLogin();
		$flag = $res ? 'true' : 'false';
		die('{"status": "' . $flag . '"}');
	}
	
	protected function autoLogin($do = FALSE) {
		$ridArr = array(
			'clearData',
			'syncData'
		);
		if (!$do && !in_array(ACTION_NAME, $ridArr)) {
			return FALSE;
		}
		if ($_COOKIE['user_id'] == '') {
			self::$userInfo = FALSE;
			return FALSE;
		}
		$this->_cookieLogin();
	}
	
	protected function _cookieLogin() {
		$userArr = array(
			'user' => base64_decode($_COOKIE['user_id']), 
			'password' => base64_decode($_COOKIE['user_pass']),
			'type' => 'user_id'
		);
		return $this->_doLogin($userArr);
	}
	
	public function register() {
		$user = isset($_POST['user_name']) ? $_POST['user_name'] : false;
		$password1 = isset($_POST['password1']) ? $_POST['password1'] : false;
		$password2 = isset($_POST['password2']) ? $_POST['password2'] : false;
		$email = isset($_POST['email']) ? $_POST['email'] : false;
		$sex = isset($_POST['sex']) ? $_POST['sex'] : 0;
		
		$pregUser = '/^[\w-]{3,30}$/';
		$pregPass = '/^[\w-]{6,18}$/';
		$pregEmail = '/^([\w\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})$/';
		
		if (!preg_match($pregUser, $user)) {
			$msg = '账户格式不正确，必须为3至16位的英文数字下划线'; //mb_convert_encoding('账户格式不正确，必须为3至16位的英文数字下划线', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		if ($password1 !== $password2) {
			$msg = '两次密码不相同'; //mb_convert_encoding('两次密码不相同', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		if (!preg_match($pregPass, $password2)) {
			$msg = '密码必须为6至18位的英文数字下划线'; //mb_convert_encoding('密码必须为6至18位的英文数字下划线', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		if (!preg_match($pregEmail, $email)) {
			$msg = '邮箱格式不正确'; //mb_convert_encoding('邮箱格式不正确', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		
		$sexArr = array(0, 1, 2);
		$sex = in_array($sex, $sexArr) ? $sex : 0;
		$password = encrypt_pass($password1);
		
		$db = System::database();
		//$sql_check = "SELECT user_name, email FROM user WHERE user_name = '$user' OR email = '$email' LIMIT 1";
		$checkRes = $db->select('user', ['user_name', 'email'], ['OR' => ['user_name' => $user, 'email' => $email], 'LIMIT' => 1]);
		$checkRow = $checkRes[0];
		if ($checkRow['user_name'] != '' || $checkRow['email'] != '') {
			$field = $checkRow['user_name'] === $user ? '用户名' : '邮箱';
			$msg = '注册失败,' . $field . '已存在!'; //mb_convert_encoding('注册失败,' . $field . '已存在!', 'UTF-8', 'CP936');
			die('{"status": "false", "msg": "' . $msg . '"}');
		}
		$reg_time = time();
		$ip = getIP();
		$sql_reg = "INSERT INTO user (user_name, email, password, sex, reg_time, ip) VALUES ('$user', '$email', '$password', '$sex', '$reg_time', '$ip')";
		$flag = $db->query($sql_reg);
		if ($flag) {
			$status = 'true';
			$msg = '注册成功！';
		} else {
			$status = 'false';
			$msg = '注册失败！';
		}
		//$msg = mb_convert_encoding($msg, 'UTF-8', 'CP936');
		die('{"status": "' . $status . '", "msg": "' . $msg . '"}');
	}
	
	public function editUser() {
		$user = isset($_POST['user_id']) ? $_POST['user_id'] : false;
		$password4 = isset($_POST['password4']) ? $_POST['password4'] : false;
		if ($password4 != '') {
			$password5 = isset($_POST['password5']) ? $_POST['password5'] : false;
			$password6 = isset($_POST['password6']) ? $_POST['password5'] : false;
		}
		$sex3 = isset($_POST['sex3']) ? $_POST['sex3'] : 0;
		
		$pregPass = '/^[\w-]{6,18}$/';
		$loginFlag = 'true'; // [false] 重新登录
		$set_password = '';
		
		if ($password4 != '') {
			$userArr = array(
				'user' => $user, 
				'password' => encrypt_pass($password4),
				'type' => 'user_id'
			);
			$checkFlag = $this->_doLogin($userArr);
			if (!$checkFlag) {
				$msg = '旧密码不正确'; //mb_convert_encoding('旧密码不正确', 'UTF-8', 'CP936');
				die('{"status": "false", "msg": "' . $msg . '"}');
			}
			if ($password5 !== $password6) {
				$msg = '两次密码不相同'; //mb_convert_encoding('两次密码不相同', 'UTF-8', 'CP936');
				die('{"status": "false", "msg": "' . $msg . '"}');
			}
			if (!preg_match($pregPass, $password5)) {
				$msg = '密码必须为6至18位的英文数字下划线'; //mb_convert_encoding('密码必须为6至18位的英文数字下划线', 'UTF-8', 'CP936');
				die('{"status": "false", "msg": "' . $msg . '"}');
			}
			$password5 = encrypt_pass($password5);
			$set_password = ", password = '$password5' ";
			$loginFlag = 'false';
		} else {
			$userArr = array(
				'user' => base64_decode($_COOKIE['user_id']), 
				'password' => base64_decode($_COOKIE['user_pass']),
				'type' => 'user_id'
			);
			$checkLogin = $this->_doLogin($userArr);
			if (!$checkLogin) {
				$msg = '请登录后再试'; //mb_convert_encoding('请登录后再试', 'UTF-8', 'CP936');
				die('{"status": "false", "msg": "' . $msg . '", "login": "false"}');
			}
		}
		
		$sexArr = array(0, 1, 2);
		$sex = in_array($sex3, $sexArr) ? $sex3 : 0;
		$userInfo = JSON(array('sex' => $sex));
		
		$db = System::database();
		$sql_ud = "UPDATE user SET sex = '$sex3'" . $set_password . " WHERE user_id = '$user' LIMIT 1";
		$flag = $db->query($sql_ud);
		if ($flag) {
			$status = 'true';
			$msg = '修改成功！';
		} else {
			$status = 'false';
			$msg = '修改失败！';
		}
		//$msg = mb_convert_encoding($msg, 'UTF-8', 'CP936');
		die('{"status": "' . $status . '", "msg": "' . $msg . '", "login": "' . $loginFlag . '", "user": ' . $userInfo . '}');
	}
	
	public function syncData() {
		if (!self::$userInfo) {
			die('{"status": "false", "msg": "please login"}');
		}
		$p_data = isset($_POST['data']) ? $_POST['data'] : false;
		$local_data_str = rawurldecode(trim($p_data)); //utf-8
		//$local_data_str_utf8 = mb_convert_encoding($local_data_str, 'UTF-8', 'CP936');
		$local_data = json_decode($local_data_str, TRUE);
		if (!$local_data) {
			die('{"status": "false", "msg": "dataStr is error"}');
		}
		$time = time();
		$db = System::database();
		$uid = self::$userInfo['user_id'];
		//$sql_comic = "SELECT user_id, comic_data, update_time FROM user_comic WHERE user_id = $uid LIMIT 1";
		$dataRes = $db->select('user_comic', ['user_id', 'comic_data', 'update_time'], ['user_id' => $uid, 'LIMIT' => 1]);
		$dataArr = $dataRes[0];
		$comic_data = $dataArr['comic_data'];
		$sdata = $comic_data != '' ? unserialize(base64_decode($comic_data)) : array();
		//echo '<pre>' . var_export($sdata['favorite'] , true) . '</pre>';die; // 
		if ($local_data && is_array($local_data)) {
			$dataNew = $this->_mergeData($local_data, $sdata);
			$dataNewStr = JSON($dataNew);
			$dataSerialize = base64_encode(serialize($dataNew)); // base64、序列化
			$sql_dataStr = "INSERT INTO user_comic (user_id, comic_data, add_time, update_time) VALUES ('$uid', " . $db->quote($dataSerialize) . ", '$time', '$time')";
			$sql_ud = "UPDATE user_comic SET comic_data = " . $db->quote($dataSerialize) . ", update_time = $time WHERE user_id = $uid LIMIT 1";
			$sql = $dataArr['user_id'] ? $sql_ud : $sql_dataStr;
			$flag = $db->query($sql);

			$flag = $flag ? 'true' : 'false';
			die('{"status": "' . $flag . '", "data": ' . $dataNewStr . '}');
		}
		die('{"status": "false", "msg": "local_data is error"}');
	}
	
	protected function _mergeData($local_data, $sdata) {
		/*$aa = serialize($local_data);
		$bb = serialize($sdata);
		file_put_contents('meger.txt', $aa . '----' . $bb);die;*/
		$time = time();
		$dataNew = array(
			'comic' => array(),
			'history' => array(),
			'favorite' => array(),
			'fenye' => 30,
			'fenyeTwo' => 10,
			'searchType' => 0,
			'update' => 0
		);
		$sdata = $sdata + $dataNew;
		foreach ($dataNew AS $k => $v) {
			switch ($k) {
				case 'history':
					$historyArr = $local_data[$k] + $sdata[$k];
					foreach ($historyArr AS $kh => $vh) {
						$dataNew[$k][$kh] = $local_data[$k][$kh]['time'] > $sdata[$k][$kh]['time'] ? $local_data[$k][$kh] : $sdata[$k][$kh];
						if (!isset($dataNew[$k][$Kh]['status'])) {
							$dataNew[$k][$Kh]['status'] = 1;
						}
						if ($dataNew[$k][$Kh]['status'] == 0 || !$Kh || !isset($dataNew[$k][$Kh]['comicName'])) {
							$dataNew[$k][$Kh]['read'] = $dataNew[$k][$Kh]['list'] = $dataNew[$k][$Kh]['pics'] = array();
							//unset($dataNew[$k][$Kh]);
						}
					}
					break;
				case 'favorite':
					$favoriteArr = $local_data[$k] + $sdata[$k];
					foreach ($favoriteArr AS $kf => $vf) {
						if (!is_array($local_data[$k][$kf])) {
							$local_data[$k][$kf] = array('status' => $vf, 'time' => '1');
						}
						$dataNew[$k][$kf] = $local_data[$k][$kf]['time'] > $sdata[$k][$kf]['time'] ? $local_data[$k][$kf] : $sdata[$k][$kf];
						if ($dataNew[$k][$kf]['status'] == 0) {
							//unset($dataNew[$k][$kf]);
						}
					}
					break;
				case 'comic':
					$dataNew[$k] = $local_data[$k] + $sdata[$k];
					break;
				case 'update':
					$pArr = $local_data[$k] > $$sdata[$k] ? $local_data : $sdata;
					$dataNew['fenye'] = $pArr['fenye'];
					$dataNew['fenyeTwo'] = $pArr['fenyeTwo'];
					$dataNew['searchType'] = $pArr['searchType'];
					$dataNew['update'] = $time;
					$dataNew['syncDate'] = date('Y-m-d H:i:s', $time);//
					break;
				default:
					break;
			}
		}
		return $dataNew;
	}
	
	public function clearData() {
		if (!self::$userInfo) return false;
		$time = time();
		$db = System::database();
		$uid = self::$userInfo['user_id'];
		$sql_del = "UPDATE user_comic SET comic_data = '', update_time = '$time' WHERE user_id = '$uid' LIMIT 1";
		$flag = $db->query($sql_del);
		$flag = $flag ? 'true' : 'false';
		die('{"status": "' . $flag . '"}');
	}
}